﻿@using PMS.Web.Models.SystemModules
@model SystemModuleModel
@{
    Layout = "_AdminHomeLayout";
    var OpenModelSelectItems = Html.GetEnumSelectList(typeof(LinkOpenMode));
    foreach (var item in OpenModelSelectItems)
    {
        item.Text = item.Value.ToEnum<LinkOpenMode>().GetDescription(true);
    }

    List<ModuleButtonModel> AllButtonModels = new List<ModuleButtonModel>();
    if (Model.CustomProperties.TryGetValue("AllButtonModels", out object buttons))
        AllButtonModels.AddRange((IList<ModuleButtonModel>)buttons);
}
@section CssStyles{ 
<style type="text/css">
    .layui-input-inline { width: 320px !important; }
    .orderSlider { margin: 16px 12px; }
    .layui-form-item .layui-card { /*Don't set width: 680px;!!*/ margin-bottom: 10px; border: 1px solid #f6f6f6; }
</style>
}
<div class="layui-container" style="background-color: #fff;">
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 10px;">
        <legend>@ViewBag.PageTitle</legend>
    </fieldset>
    <form class="layui-form" action="">
        <input class="layui-hide" type="text" name="@Model.NameOf(m => m.Id)" value="@Model.Id" />
        <div class="layui-form-item">
            <label class="layui-form-label">@Model.DisplayName(m => m.ParentModuleId)</label>
            <div class="layui-input-inline">
                <div id="parentModuleId" class="dtree" data-id="@Model.Id" data-value="@Model.ParentModuleId"></div>
                <input type="text" name="@Model.NameOf(m => m.ParentModuleId)" value="@Model.ParentModuleId" class="layui-hide">
            </div>
            <div class="layui-form-mid layui-word-aux">
                <button type="button" id="clearParentBtnId" class="pear-btn pear-btn-danger pear-btn-sm"> 清除选择 </button>
                若清除选择,则模块放置在根节点位置(与"首页"平级放置)
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">@Model.DisplayName(m => m.HtmlIconCSSClass)</label>
            <div class="layui-input-inline">
                <input type="text" id="IconCssClass" name="@Model.NameOf(m => m.HtmlIconCSSClass)" value="@Model.HtmlIconCSSClass" lay-filter="iconFonts" required lay-verify="required" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">@Model.DisplayName(m => m.Name)</label>
            <div class="layui-input-inline">
                <input type="text" name="@Model.NameOf(m => m.Name)" value="@Model.Name" lay-verify="required" placeholder="请输入系统模块名称" autocomplete="off" class="layui-input">
            </div>
            <div class="layui-form-mid layui-word-aux">建议使用英文，区分大小写</div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">@Model.DisplayName(m => m.DisplayName)</label>
            <div class="layui-input-inline">
                <input type="text" name="@Model.NameOf(m => m.DisplayName)" value="@Model.DisplayName" placeholder="请输入显示名称" autocomplete="off" class="layui-input">
            </div>
            <div class="layui-form-mid layui-word-aux">如不填写，则使用系统模块名做显示</div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">@Model.DisplayName(m => m.ModuleDescription)</label>
            <div class="layui-input-inline">
                <textarea name="@Model.NameOf(m => m.ModuleDescription)" placeholder="请简述模块功能" class="layui-textarea">@Model.ModuleDescription</textarea>
            </div>
            <div class="layui-form-mid layui-word-aux"></div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">@Model.DisplayName(m => m.OpenMode)</label>
            <div class="layui-input-inline">
                <select asp-for="OpenMode" asp-items="@OpenModelSelectItems" lay-verify="required" lay-filter="OpenModelSelect">
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">@Model.DisplayName(m => m.RouteUrl)</label>
            <div class="layui-input-inline">
                <input type="text" name="@Model.NameOf(m => m.RouteUrl)" value="@Model.RouteUrl" lay-verify="requiredwhenmodulepage" placeholder="请选输入Url" autocomplete="off" class="layui-input">
            </div>
            <div class="layui-form-mid layui-word-aux">当系统模块打开方式非"无链接导航"时，此项不能为空</div>
        </div>
        <div class="layui-form-item">
            <div class="layui-col-xs6 layui-col-sm6 layui-col-md6">
                <label class="layui-form-label">@Model.DisplayName(m => m.DisplayOrder)</label>
                <div class="layui-input-inline">
                    <div id="orderSlider" class="orderSlider"></div>
                    <input type="text" class="layui-hide" name="@Model.NameOf(m => m.DisplayOrder)" value="@Model.DisplayOrder" />
                </div>
            </div>
            <div class="layui-col-xs6 layui-col-sm6 layui-col-md6">
                <label class="layui-form-label">@Model.DisplayName(m => m.IsActive)</label>
                <div class="layui-input-inline">
                    <input type="checkbox" name="@Model.NameOf(m => m.IsActive)" value="@Model.IsActive.ToString()" lay-skin="switch" lay-text="ON|OFF" lay-filter="IsActiveSwitch" @if (Model.IsActive) { <text> checked</text> } />
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">@Model.DisplayName(m => m.LimitedStoreIds)</label>
            <div class="layui-input-inline">
                <div id="storeselect" class="xmselect"></div>
                <input type="text" class="layui-hide" name="@Model.NameOf(m => m.LimitedStoreIds)" value="@(string.Join(',', Model.LimitedStoreIds))" />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">@Model.DisplayName(m => m.ModuleAssignedButtonIds)</label>
            @foreach (var item in typeof(ModuleButtonGroup).GetEnumValues())
            {
                <div class="layui-card layui-input-block">
                    <div class="layui-card-header">
                        @(((ModuleButtonGroup)item).GetDescription())
                    </div>
                    <div class="layui-card-body">
                        @foreach (var btnitem in AllButtonModels.Where(b => b.GroupType == (ModuleButtonGroup)item))
                        {
                            <input type="checkbox"
                                   name="modulebtn"
                                   value="@btnitem.Id"
                                   title="@btnitem.Name"
                                   lay-skin="primary"
                                   @if (Model.OpenMode == LinkOpenMode.None) { <text> disabled</text> }
                                   @if (Model.ModuleAssignedButtonIds.Any(abid => abid == btnitem.Id)) { <text> checked</text> } />
                        }
                    </div>
                </div>
            }
        </div>
        <div style="width: 100%; height: 50px; line-height: 50px;"></div> <!--占位符，防止底部固定提交栏遮挡最下层区域-->
        <div class="layui-form-item footerbar">
            <div class="layui-input-block">
                <button class="pear-btn pear-btn-primary pear-btn-sm" lay-submit lay-filter="systemmoduleedit">提交保存</button>
            </div>
        </div>
    </form>
    @await Component.InvokeAsync("ModelValidateError")
</div>

@section Scripts{
    <script type="text/javascript">
        layui.use(['form', 'element', 'iconPicker', 'slider', 'dtree', 'Cookies', 'http', 'xmSelect', 'loading', 'popup', 'laytpl', 'lodash'], function () {
            var form = layui.form,
                element = layui.element,
                iconPicker = layui.iconPicker,
                slider = layui.slider,
                dtree = layui.dtree,
                Cookies = layui.Cookies,
                $ = layui.jquery,
                http = layui.http,
                xmSelect = layui.xmSelect,
                loading = layui.loading,
                popup = layui.popup,
                laytpl = layui.laytpl,
                lodash = layui.lodash;

            var limitedStoreIds = [],
                storeSelector = null;

            const initPageComponents = function () {
                //图标选择
                iconPicker.render({
                    elem: '#IconCssClass',
                    type: 'fontClass',
                    search: true,
                    page: true,
                    limit: 16,
                    click: function (data) {
                        let iconclass = data.icon;
                        if (!iconclass.startsWith("layui-icon ")) iconclass = 'layui-icon ' + data.icon;
                        $(data.elem).val(iconclass);
                    },
                });
                 //滑动组件
                let $order = $("input[name=DisplayOrder]");
                slider.render({
                    elem: '#orderSlider'
                    , min: 1
                    , max: 150
                    , input: true //输入框
                    , theme: '#1E9FFF' //主题色
                    , value: $order.val()
                    , change: function (value) {
                        $order.val(value);
                    }
                });
                //父级下拉树框
                const ParentNodeTree = dtree.render({
                    elem: "#parentModuleId",
                    width: "100%", // 指定树的宽度
                    url: backendwebapiConfig.getsystemmenusall,
                    select: true,
                    skin: "laySimple",
                    async: true,
                    method: "get",
                    selectTips: "请选择父节点",
                    selectCardHeight: "350",
                    dataStyle: "layuiStyle",
                    withCredentials: true,
                    beforeSend: function (ajax, xhr, self) {
                        const cookieVal = Cookies.get(".PMS.SignInToken");
                        if (cookieVal != null)
                            xhr.setRequestHeader("Authorization", "Bearer " + cookieVal);
                        return true;
                    },
                    done: function (result, $ul, first) {
                        const $ModuldId = $("input[name=Id]");
                        if ($ModuldId.val() !== "0")
                            ParentNodeTree.setDisabledNodes($ModuldId.val()); // 设置本节点禁用
                    },
                    response: {
                        message: "msg",
                        statusCode: 200,
                        treeId: "id",
                        parentId: "parentid"
                    },
                    success: function (response) {
                        if (response.state && response.state === 200) {
                            var menu = response.data;
                            if (PMSUtils.isString(menu))
                                menu = JSON.parse(response.data);
                            return {
                                code: response.state,
                                msg: response.message,
                                data: PMSUtils.toArrayTree(menu, { strict: true, parentKey: 'parentid', key: 'id', children: 'children', sortKey: 'order' })
                            };
                        }
                        return {
                            code: -1,
                            msg: response.message,
                            data: null
                        };
                    }
                });
                dtree.on('node("parentModuleId")', function (obj) {
                    var param = dtree.selectVal("parentModuleId");
                    $("input[name=ParentModuleId]").val(param.parentModuleId_select_nodeId);
                });
                $("#clearParentBtnId").click(function () {
                    ParentNodeTree.selectResetVal();
                    $("input[name=ParentModuleId]").val("0");
                });
                //点击任何地方关闭下拉框树
                $("body").on("click", function (event) {
                    $("div[dtree-id][dtree-select]").removeClass("layui-form-selected");
                    $("div[dtree-id][dtree-card]").removeClass("dtree-select-show layui-anim layui-anim-upbit");
                });

                //是否指定店铺
                storeSelector = xmSelect.render({
                    el: '#storeselect',
                    tips: '可选择系统模块只应用于某几个店铺',
                    autoRow: true,
                    height: 'auto',
                    data: [],
                    toolbar: { show: true },
                    template({ item, sels, name, value }) {
                        return item.name + '<span style="position: absolute; right: 10px; color: #8799a3">' + item.url + '</span>'
                    },
                    on: function (data) {
                        const selected = data.arr;
                        limitedStoreIds = lodash.map(selected, function (item) {
                            return PMSUtils.toNumber(item.value);
                        });
                    }
                });
                const $openModeSelect = $("select[name='OpenMode']"); //None : 1 ; IFrame : 2
                http.get(backendwebapiConfig.getstoreselectlist, null, null)
                    .done(function (response) {
                        //所属店铺
                        const storeIdStr = $("input[name=LimitedStoreIds]").val();
                        if (storeIdStr.length > 0) {
                            limitedStoreIds = lodash.map(lodash.split(storeIdStr, ','), function (id) {
                                return PMSUtils.toNumber(id);
                            });
                        }
                        if (response.state && response.state === 200) {
                            let data = response.data;
                            if (PMSUtils.isString(data))
                                data = $.parseJSON(response.data);
                            storeSelector.update({
                                data: data,
                                initValue: limitedStoreIds,
                                disabled: ($openModeSelect.val() === "1") ? true : false
                            });
                        }
                    });
            };
            initPageComponents();

            const disableModuleButtons = function (isNavModule) {
                //只有系统模块（OpenMode == IFrame）可以分配操作按钮
                var $btns = $("input[name='modulebtn']");
                if (isNavModule) {
                    $("input[name='modulebtn']:checked").prop("checked", false);
                    $btns.attr("disabled", "disabled");
                } else {
                    $btns.removeAttr("disabled");
                }
                form.render();
            };
            // 注：系统模块权限分配遵循原则：
            // OpenMode = IFrame 且 RouteUrl不为空 认为是系统模块页面(即功能页)
            // 功能页才能分配指定店铺
            // 而导航菜单(即分类菜单)不能分配店铺，故查询时(包括新增/修改系统模块时)要注意模块数据关系
            form.on('select(OpenModelSelect)', function (data) {
                const isNavModule = data.value === "1"; //None : 1 ; IFrame : 2
                if (isNavModule) {
                    limitedStoreIds = [];
                    storeSelector.setValue(limitedStoreIds);
                    $("input[name=RouteUrl]").val("");
                }
                xmSelect.batch('#storeselect', 'update', {
                    disabled: isNavModule
                });
                disableModuleButtons(isNavModule);
            });   

            //更新状态
            form.on('switch(IsActiveSwitch)', function (data) {
                $(data.elem).val((data.elem.checked) ? "True" : "False");
                form.render('checkbox');
            });  
            form.verify({
                requiredwhenmodulepage: function (value, item) { //value：表单的值、item：表单的DOM对象
                    let $openModeSelect = $("select[name='OpenMode']"); //None : 1 ; IFrame : 2
                    if ($openModeSelect.val() !== "") {
                        if ($openModeSelect.val() !== "1" && value.trim() === "") {
                            $(item).focus();
                            return "当系统模块类型为'系统模块'时，Url不能为空";
                        }
                    }
                }
            });  
            //监听提交
            var confirmPost = function (confirm, postData) {
                http.post(backendwebapiConfig.systemmoduleedit + "?changebtnauth=" + confirm,
                    postData,
                    function () { //beforeSend
                        loading.block({ type: 1, elem: '.layui-container', msg: '保存提交中,请稍候...' })
                    }
                ).done(function (response) {
                    if (response.state && response.state === 200) {
                        popup.success(response.message, function () {
                            PMSUtils.closePopupWindow();
                        });
                    }
                }).fail(function (error) {
                    //For ModelValidation
                    if (error.status && error.status === 400) {
                        var validator = error.responseJSON;
                        if (validator.ErrorCode && validator.ErrorCode === "FluentValidationError") {
                            var validateTpl = document.getElementById('validateResultTpl').innerHTML;
                            laytpl(validateTpl).render(validator, function (html) {
                                http.ajax.showError({
                                    message: '提示信息',
                                    details: html
                                });
                            });
                            //标红校验错误的数据框
                            layui.each(validator.Errors, function (index, item) {
                                var inputField = item.ErrorField;
                                $("input[name=" + inputField + "]").attr('failure', '');
                            });
                        }
                    }
                }).always(function () {
                    loading.blockRemove(".layui-container", 1000);
                });
            };
            form.on("submit(systemmoduleedit)", function (data) {
                var postData = data.field;

                postData.ModuleAssignedButtonIds = lodash.map($("input[name='modulebtn']:checked"), function (btnEl) {
                    return PMSUtils.toNumber($(btnEl).val());
                });

                if (PMSUtils.hasOwnProp(postData, "modulebtn")) {
                    PMSUtils.remove(postData, "modulebtn");
                }
                if (PMSUtils.hasOwnProp(postData, "parentModuleId_select_nodeId")) {
                    PMSUtils.remove(postData, function (value, prop) {
                        return prop.indexOf("parentModuleId_select") >= 0;//["parentModuleId_select_input", "parentModuleId_select_nodeId"];
                    });
                }
                if (PMSUtils.hasOwnProp(postData, "select")) {
                    PMSUtils.remove(postData, "select");
                }
                postData.LimitedStoreIds = limitedStoreIds;
                //console.log(postData);
                http.post(backendwebapiConfig.checkassignedbuttonschangeresult + "?moduleId=" + postData.Id,
                    postData.ModuleAssignedButtonIds
                ).done(function (response) {
                    if (response.state && response.state === 200) {
                        if (response.data.CheckResult) {
                            layer.confirm(response.message, { icon: 3, title: '提示' }, function (index) {
                                layer.close(index); //注意执行顺序，否则弹出框无法关闭
                                confirmPost(true, postData);
                            });
                        } else confirmPost(false, postData);
                    }
                });

                
                return false;
            });
        });
    </script>
}
